/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chatNI;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Observable;
import java.io.IOException;
import static java.lang.Thread.interrupted;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import signals.SignalTooBigException;

/* 
 * @author deepali and vansh 
 */
public class ThreadReceiveMsg extends Thread {

    /**
     * @param cni is the instance of the chat network interface that we are
     * using
     * @param rcvMsgSock represents the socket that we use to receive a message
     * @param port is the port for this application
     */
    private static ChatNI cni;
    private static DatagramSocket rcvMsgSock;
    private int port;

    public ThreadReceiveMsg(ChatNI cni, int port) {
        this.cni = cni;
        this.port = port;
    }

    /**
     * A thread to receive the message as datagram packet is run.
     */
    public void run() {
        DatagramPacket packet;
        byte[] msgRcvd;
        try {
            rcvMsgSock = new DatagramSocket(port);
            int bufferSize = rcvMsgSock.getReceiveBufferSize();
            while (!interrupted()) {
                msgRcvd = new byte[bufferSize];
                packet = new DatagramPacket(msgRcvd, msgRcvd.length);
                rcvMsgSock.receive(packet);
                cni.Receive(packet);
            }
            rcvMsgSock.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ThreadReceiveMsg.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignalTooBigException ex) {
            Logger.getLogger(ThreadReceiveMsg.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
